package drp.snowbell.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import drp.snowbell.util.file.FileUtility;


/**
 * 文件资源
 * 
 * @author jimmy
 * 
 */
public class FileResource implements IResource {

	private File resource;
	private URI uri;

	public FileResource(URI uri) {
		this.uri = uri;
		File file = new File(uri);
		this.resource = file;
	}

	public File getFile() {
		return resource;
	}

	@Override
	public URI getURI() {
		return uri;
	}

	// @Override
	// public boolean isDirectory() {
	// return resource.isDirectory();
	// }

	// @Override
	// public IResource[] listResource() {
	// IResource[] ret = null;
	// File[] files = resource.listFiles();
	// if (files != null) {
	// ret = new IResource[files.length];
	// for (int i = 0; i < files.length; i++) {
	// URI fileUri = getUri(files[i]);
	// ret[i] = new FileResource(fileUri);
	// }
	// }
	// return ret;
	// }

	@Override
	public String getName() {
		return resource.getName();
	}

	@Override
	public InputStream openInputStream() {
		try {
			return new FileInputStream(resource);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public OutputStream openOutStream() {
		try {
			return new FileOutputStream(resource);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean rename(String newName) {
		String path = resource.getParent() + File.separator + newName;
		File dest = FileUtility.getFile(path);
		// if (dest.exists()) {
		// dest.delete();
		// }
		boolean ret = resource.renameTo(dest);
		return ret;
	}

	@Override
	public boolean delete() {
		return resource.delete();
	}

	// private URI getUri(File file) {
	// URI ret = null;
	// try {
	// ret = new URI(ResourceCenter.FILE_SCHEME, file.getPath(), null);
	// } catch (URISyntaxException e) {
	// CatchException.take(FileResource.class, e);
	// }
	// return ret;
	// }

	@Override
	public String getPath() {
		return resource.getPath();
	}

}
